<template>
  <div class="friend-tags-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>好友管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleSendMessage" :disabled="selectedFriends.length === 0 || !isAccountOnline">发送消息</el-button>
            <el-button type="primary" @click="openBatchTagDialog" :disabled="selectedFriends.length === 0">设置标签</el-button>
            <el-button type="primary" @click="openBatchRemoveTagDialog" :disabled="selectedFriends.length === 0">移除标签</el-button>            
            <!-- <el-button type="primary" @click="handleSetAsCustomer" :disabled="selectedFriends.length === 0">设置为客户</el-button>             -->
            <el-button type="primary" @click="handleAddFriend">添加好友</el-button>
            <el-button type="primary" @click="handleTagManagement">标签管理</el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-container">
        <el-input
          v-model="searchQuery"
          placeholder="搜索好友名称"
          class="search-input"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>
        
        <el-select 
          v-model="accountFilter" 
          placeholder="选择账号" 
          clearable 
          @change="handleAccountChange" 
          class="filter-select"
          :loading="accountsLoading"
        >
          <template #prefix>
            <el-icon><UserFilled /></el-icon>
          </template>
          <template #empty>
            <div class="empty-data">
              <p v-if="accountsLoading">正在加载账号列表...</p>
              <p v-else>暂无在线账号</p>
            </div>
          </template>
          <el-option
            v-for="account in accountOptions"
            :key="account.id"
            :label="account.name"
            :value="account.id"
          >
            <div class="account-option">
              <el-avatar :size="24" :src="account.avatar" class="account-avatar" />
              <span>{{ account.name }}</span>
              <el-tag size="small" :type="account.status === 'online' ? 'success' : 'info'" class="account-status">
                {{ account.status === 'online' ? '在线' : '离线' }}
              </el-tag>
            </div>
          </el-option>
        </el-select>
        
        <el-select v-model="tagFilter" placeholder="标签筛选" clearable @change="handleSearch" class="filter-select">
          <template #empty>
            <div class="empty-data">
              <p>请先选择账号</p>
            </div>
          </template>
          <el-option
            v-for="tag in tagOptions"
            :key="tag.value"
            :label="tag.label"
            :value="tag.value"
          />
        </el-select>
      </div>
      
      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="friendList"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="nickname" label="昵称" />
        <el-table-column prop="wxid" label="微信ID" />
        <el-table-column label="标签">
          <template #default="{ row }">
            <el-tag
              v-for="tag in row.tags"
              :key="tag.value"            
              class="tag-item"
            >
              {{ tag.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'info'">
              {{ row.status === 'active' ? '活跃' : '非活跃' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewDetail(row)">查看详情</el-button>
            <el-button
              v-if="hasPermission(Permission.MANAGE_FRIEND_TAGS)"
              type="danger"
              link
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

      <!-- 批量操作工具栏已移除 -->
        <!-- 添加发送消息对话框 -->
    <el-dialog v-model="messageDialogVisible" title="消息内容" width="600px">
      <div class="message-dialog-container">
        <div class="recipient-info" v-if="selectedFriends.length > 0">
          <span>收件人：</span>
          <div class="recipients">
            <el-avatar
              v-for="friend in selectedFriends"
              :key="friend.id"
              :src="friend.accountAvatar"
              :size="32"
              :title="friend.nickname"
              class="recipient-avatar"
            />
          </div>
        </div>
        <el-input
          v-model="messageContent"
          type="textarea"
          rows="8"
          placeholder="请输入消息内容..."
          class="message-textarea"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="messageDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSendMessageConfirm">发送</el-button>
        </span>
      </template>
    </el-dialog>

    
    <!-- 标签编辑对话框 -->
    <el-dialog v-model="tagDialogVisible" title="编辑标签" width="500px">
      <div class="tag-edit-container">
        <div class="current-tags">
          <span>当前标签：</span>
          <el-tag
            v-for="tag in currentFriend.tags"
            :key="tag.id"
            :type="tag.type"
            closable
            @close="handleRemoveTag(tag)"
          >
            {{ tag.name }}
          </el-tag>
        </div>
        <div class="add-tag">
          <el-select
            v-model="selectedTag"
            filterable
            allow-create
            default-first-option
            placeholder="请选择或创建标签"
          >
            <el-option
              v-for="tag in availableTags"
              :key="tag.value"
              :label="tag.label"
              :value="tag.value"
            />
          </el-select>
          <el-button type="primary" @click="handleAddTag">添加标签</el-button>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="tagDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveTagChanges">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 标签管理对话框 -->
    <el-dialog v-model="tagManagementDialogVisible" title="标签管理" width="600px">
      <div class="tag-management-container">
        <div class="tag-creation">
          <el-input
            v-model="newTagName"
            placeholder="输入新标签名称"
            class="tag-input"
          >
            <template #append>
              <el-button type="primary" @click="handleCreateTag">创建标签</el-button>
            </template>
          </el-input>
        </div>

        <el-divider />

        <div class="tag-list">
          <el-table
            v-loading="tagLoading"
            :data="allTags"
            style="width: 100%"
            border
          >
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="标签名称" />
            <el-table-column label="操作" width="100">
              <template #default="{ row }">
                <!-- 客户标签不能删除 -->
            <el-button
              type="danger"
              link
              @click="handleDeleteTag(row)"
              :disabled="row.name === '客户'"
            >
              删除
            </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="tagManagementDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加好友对话框 -->
    <el-dialog v-model="addDialogVisible" title="添加好友" width="500px">
      <el-form :model="newFriend" label-width="100px">
        <el-form-item label="昵称" required>
          <el-input v-model="newFriend.nickname" />
        </el-form-item>
        <el-form-item label="微信ID" required>
          <el-input v-model="newFriend.wxid" />
        </el-form-item>
        <el-form-item label="标签">
          <el-select
            v-model="newFriend.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或创建标签"
          >
            <el-option
              v-for="tag in availableTags"
              :key="tag.value"
              :label="tag.label"
              :value="tag.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveFriend">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 批量标签设置对话框 -->
    <el-dialog v-model="batchTagDialogVisible" title="批量设置标签" width="500px">
      <div class="batch-tag-container">
        <p>已选择 {{ selectedFriends.length }} 位好友</p>
        <el-select
          v-model="selectedBatchTag"
          filterable
          allow-create
          default-first-option
          placeholder="请选择或创建标签"
          class="tag-select"
        >
          <el-option
            v-for="tag in availableTags"
            :key="tag.value"
            :label="tag.label"
            :value="tag.value"
          />
        </el-select>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchTagDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="batchSetTags">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量标签移除对话框 -->
    <el-dialog v-model="batchRemoveTagDialogVisible" title="批量移除标签" width="500px">
      <div class="batch-tag-container">
        <p>已选择 {{ selectedFriends.length }} 位好友</p>
        <el-select
          v-model="selectedRemoveTag"
          filterable
          default-first-option
          placeholder="请选择要移除的标签"
          class="tag-select"
        >
          <el-option
            v-for="tag in availableTags"
            :key="tag.value"
            :label="tag.label"
            :value="tag.value"
          />
        </el-select>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchRemoveTagDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="batchRemoveTags">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设置为客户结果提示 -->
    <el-dialog v-model="customerResultDialogVisible" :title="customerResultSuccess ? '操作成功' : '操作失败'" width="400px">
      <div class="result-message">
        <el-icon v-if="customerResultSuccess" class="success-icon" :size="48"><CircleCheckFilled /></el-icon>
        <el-icon v-else class="error-icon" :size="48"><CircleCloseFilled /></el-icon>
        <p>{{ customerResultMessage }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="customerResultDialogVisible = false">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 好友详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="好友详情" width="600px">
      <div v-if="friendDetail" class="friend-detail">
        <!-- 基本信息 -->
        <div class="basic-info">
          <div class="avatar-section">
            <el-avatar :size="80" :src="friendDetail.bigHeadImgUrl" />
            <div class="name-info">
              <h3>{{ friendDetail.nickName?.str || '未知昵称' }}</h3>
              <p class="wxid">{{ friendDetail.userName?.str || '未知微信ID' }}</p>
              <p class="alias" v-if="friendDetail.alias">微信号：{{ friendDetail.alias }}</p>
            </div>
          </div>
          
          <div class="status-info">
            <el-tag :type="friendDetail.sex === 1 ? 'primary' : friendDetail.sex === 2 ? 'danger' : 'info'">
              {{ friendDetail.sex === 1 ? '男' : friendDetail.sex === 2 ? '女' : '未知' }}
            </el-tag>
            <el-tag type="success" v-if="friendDetail.verifyFlag === 1">已认证</el-tag>
          </div>
        </div>

        <!-- 详细信息 -->
        <el-divider />
        <div class="detail-info">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="info-item">
                <label>昵称：</label>
                <span>{{ friendDetail.nickName?.str || '-' }}</span>
              </div>
              <div class="info-item">
                <label>拼音：</label>
                <span>{{ friendDetail.pyinitial?.str || '-' }}</span>
              </div>
              <div class="info-item">
                <label>全拼：</label>
                <span>{{ friendDetail.quanPin?.str || '-' }}</span>
              </div>
              <div class="info-item">
                <label>来源：</label>
                <span>{{ getSourceText(friendDetail.source) }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>等级：</label>
                <span>{{ friendDetail.level || 0 }}</span>
              </div>
              <div class="info-item">
                <label>个人名片：</label>
                <span>{{ friendDetail.personalCard === 1 ? '是' : '否' }}</span>
              </div>
              <div class="info-item">
                <label>高清头像：</label>
                <span>{{ friendDetail.hasWeiXinHdHeadImg === 1 ? '是' : '否' }}</span>
              </div>
              <div class="info-item">
                <label>添加场景：</label>
                <span>{{ getAddContactSceneText(friendDetail.addContactScene) }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 备注编辑 -->
        <el-divider />
        <div class="remark-section">
          <div class="remark-header">
            <h4>备注信息</h4>
            <div class="remark-actions">
              <el-button type="primary" size="small" @click="handleViewHistory">查看历史聊天记录</el-button>
              <el-button type="primary" size="small" @click="handleEditRemark">编辑备注</el-button>
            </div>
          </div>
          <div v-if="!isEditingRemark" class="remark-content">
            <div v-if="friendDetail.remark?.str" v-html="parseMarkdown(friendDetail.remark.str)"></div>
            <p v-else class="no-remark">暂无备注</p>
          </div>
          <div v-else class="remark-edit">
            <div class="edit-tools" style="margin-bottom: 10px;">
              <el-button size="small" @click="formatJsonContent" v-if="isJsonContent(editingRemark)">格式化JSON</el-button>
              <el-button size="small" @click="minifyJsonContent" v-if="isJsonContent(editingRemark)">压缩JSON</el-button>
            </div>
            <el-input
              v-model="editingRemark"
              type="textarea"
              :rows="10"
              placeholder="请输入备注信息"
              style="font-family: 'Courier New', Courier, monospace;"
            />
            <div class="remark-actions">
              <el-button size="small" @click="cancelEditRemark">取消</el-button>
              <el-button type="primary" size="small" @click="saveRemark">保存</el-button>
            </div>
          </div>
        </div>

        <!-- 标签信息 -->
        <el-divider />
        <div class="tags-section">
          <h4>标签信息</h4>
          <div class="current-tags">
            <el-tag
              v-for="tag in currentFriend.tags"
              :key="tag.value"
              class="tag-item"
            >
              {{ tag.name }}
            </el-tag>
            <span v-if="currentFriend.tags.length === 0" class="no-tags">暂无标签</span>
          </div>
        </div>
      </div>
      
      <div v-else class="loading-detail">
        <el-skeleton :rows="6" animated />
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 历史聊天记录弹窗 -->
    <el-dialog v-model="historyDialogVisible" title="历史聊天记录" width="800px" class="history-dialog">
      <div v-if="chatHistory.length > 0" class="chat-history">
        <div v-for="(message, index) in chatHistory" :key="index" :class="['message-item', message.is_sent ? 'sent' : 'received']">
          <div class="message-time">{{ formatMessageTime(message.timestamp) }}</div>
          <div class="message-content" :class="{ 'message-sent': message.is_sent, 'message-received': !message.is_sent }">
            <div class="message-text">{{ message.content }}</div>
            <div class="message-type">
              <el-tag size="small" :type="getMessageTypeTag(message.type)">
                {{ getMessageTypeText(message.type) }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>
      <div v-else-if="historyLoading" class="loading-history">
        <el-skeleton :rows="5" animated />
      </div>
      <div v-else class="empty-history">
        <el-empty description="暂无聊天记录" />
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="historyDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, reactive, computed} from 'vue'
import { Search, CircleCheckFilled, CircleCloseFilled, UserFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Permission, hasPermission } from '@/utils/permission'
import axios from 'axios'

// 增强的Markdown解析函数 - 支持普通Markdown和JSON文本转换
const parseMarkdown = (text: string): string => {
  if (!text) return '';
  
  // 尝试将文本解析为JSON对象
  let parsedJson;
  try {
    // 更健壮的JSON清理方法，保留引号内的空格和换行
    let cleanText = text.trim();
    
    // 处理常见的JSON格式问题
    // 1. 移除前后可能的代码块标记
    cleanText = cleanText.replace(/^```json\s*|\s*```$/g, '');
    // 2. 移除可能的逗号错误
    cleanText = cleanText.replace(/,\s*}\s*$/, '}').replace(/,\s*]\s*$/, ']');
    // 3. 修复可能的字符串引号问题
    cleanText = cleanText.replace(/([^\\])'([^']+)([^\\])'/g, '$1"$2$3"');
    
    parsedJson = JSON.parse(cleanText);
    // 如果是JSON对象，转换为Markdown格式
    return convertJsonToMarkdown(parsedJson);
  } catch (e) {
    // 输出解析错误到控制台以便调试
    console.log('JSON解析失败，按普通文本处理:', e);
  }
  
  // 预处理文本，规范化换行符
  let preprocessedText = text.replace(/\r\n/g, '\n');
  
  let result = preprocessedText
    // 先处理粗体文本
    .replace(/\*\*([^\*]+)\*\*/g, '<strong>$1</strong>')
    // 标题处理 - 增强支持带星号和不带星号的中文数字序号标题
    .replace(/^(?:\*\*)?(一、|二、|三、|四、|五、|六、|七、|八、|九、|十、)[^\n]+(?:\*\*)?/gm, '<h4 class="markdown-heading">$&</h4>')
    // 结论标题处理
    .replace(/^(?:\*\*)?结论(?:\*\*)?：/gm, '<h4 class="markdown-heading">结论：</h4>')
    // 列表项处理 - 支持带点的列表
    .replace(/^\s*•\s+([^\n]+)/gm, '<li>$1</li>')
    // 替换原始的连字符列表格式
    .replace(/^\-\s+([^\n]+)/gm, '<li>$1</li>')
    // 将连续的li标签包装成ul
    .replace(/(<li>.*?<\/li>)(?=\s*<li>|\s*$)/gs, (match) => `<ul class="markdown-list">${match}</ul>`)
    // 处理分隔线
    .replace(/^---$/gm, '<hr class="markdown-divider">')
    // 段落处理 - 排除已处理的元素
    .replace(/^(?!<ul|<li|<hr|<strong|<h4)([^\n]+)/gm, '<p>$1</p>');
    
  return result;
}

// 将JSON对象转换为Markdown格式的函数
const convertJsonToMarkdown = (json: any): string => {
  let markdown = '';
  
  // 处理不同类型的JSON数据
  if (typeof json === 'object' && json !== null) {
    if (Array.isArray(json)) {
      // 处理数组
      markdown += '<ul class="markdown-list">';
      json.forEach((item, index) => {
        if (typeof item === 'object' && item !== null) {
          // 数组中包含对象
          markdown += `<li>项目 ${index + 1}:</li>`;
          markdown += '<ul class="markdown-list">';
          for (const [key, value] of Object.entries(item)) {
            markdown += `<li>${key}：${typeof value === 'object' ? JSON.stringify(value) : value}</li>`;
          }
          markdown += '</ul>';
        } else {
          // 数组中包含简单值
          markdown += `<li>${String(item)}</li>`;
        }
      });
      markdown += '</ul>';
    } else {
      // 处理对象
      for (const [key, value] of Object.entries(json)) {
        // 添加顶级标题
        markdown += `<h4 class="markdown-heading">${key}</h4>`;
        markdown += '<ul class="markdown-list">';
        
        // 如果值是对象，遍历其属性
        if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
          for (const [subKey, subValue] of Object.entries(value)) {
            // 添加列表项
            markdown += `<li>${subKey}：${String(subValue)}</li>`;
          }
        } else if (Array.isArray(value)) {
          // 如果是数组
          value.forEach((item, index) => {
            markdown += `<li>项目 ${index + 1}：${String(item)}</li>`;
          });
        } else {
          // 简单值直接显示
          markdown += `<li>${String(value)}</li>`;
        }
        
        markdown += '</ul>';
      }
    }
  } else {
    // 简单值直接显示
    markdown = `<p>${String(json)}</p>`;
  }
  
  return markdown;
}

// 定义类型
interface Tag {
  id: string;
  name: string;
  value: string;
  type: string;
}

interface Friend {
  id: number;
  nickname: string;
  wxid: string;
  status: string;
  tags: Tag[];
  account: string;
  accountName: string;
  accountAvatar: string;
  token_key: string;
}

interface Account {
  id: string;
  name: string;
  avatar: string;
  status: 'online' | 'offline';
  auth_key: string;
}

// 分页相关
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 搜索相关
const searchQuery = ref('')
const tagFilter = ref('')

// 加载状态
const loading = ref(false)
const accountsLoading = ref(false)

// 好友列表数据
const friendList = ref<Friend[]>([])

// 选中的好友
const selectedFriends = ref<Friend[]>([])

// 设置为客户结果相关
const customerResultDialogVisible = ref(false)
const customerResultSuccess = ref(true)
const customerResultMessage = ref('')

// 所有标签列表（从服务器获取或本地维护）
const allTags = ref([
  { id: '1', name: '客户', value: '客户', type: 'default' },
  { id: '2', name: '家人', value: '家人', type: 'default' },
  { id: '3', name: '同事', value: '同事', type: 'default' },
  { id: '4', name: '重要', value: '重要', type: 'default' },
  { id: '5', name: '商业', value: '商业', type: 'default' },
  { id: '6', name: '同学', value: '同学', type: 'default' },
  { id: '7', name: '其他', value: '其他', type: 'default' }
])

// 标签选项（用于筛选）
const tagOptions = computed(() => {
  return allTags.value.map(tag => ({
    value: tag.name,
    label: tag.name
  }))
})

// 可用标签（用于选择和创建）
const availableTags = computed(() => {
  return allTags.value.map(tag => ({
    value: tag.name,
    label: tag.name
  }))
})

// 标签管理相关
const tagManagementDialogVisible = ref(false)
const newTagName = ref('')
const tagLoading = ref(false)

// 初始化标签列表
const initTags = async () => {
  tagLoading.value = true;
  try {
    // 调用后端获取标签接口
      const response = await axios.get('/tags', {
        params: {
          device_id: accountFilter.value
        }
      });
      
      // 更新标签列表 - 后端返回的是字符串数组
      const tags = (response.data.data || []).map((tagName: string, index: number) => ({
        id: index + 1, // 为标签生成唯一ID
        name: tagName,
        value: tagName,
        type: 'default'
      }));
      
      // 确保客户标签在第一位
      allTags.value = sortTags(tags);
  } catch (error) {
    console.error('获取标签列表失败:', error);
    ElMessage.error('获取标签列表失败');
    // 出错时使用默认标签
    allTags.value = sortTags([
      { id: '1', name: '客户', value: '客户', type: 'default' },
      { id: '2', name: '家人', value: '家人', type: 'default' },
      { id: '3', name: '同事', value: '同事', type: 'default' },
      { id: '4', name: '重要', value: '重要', type: 'default' },
      { id: '5', name: '商业', value: '商业', type: 'default' },
      { id: '6', name: '同学', value: '同学', type: 'default' },
      { id: '7', name: '其他', value: '其他', type: 'default' }
    ]);
  } finally {
    tagLoading.value = false;
  }
}

// 在组件挂载时初始化标签和账号
onMounted(() => {
  fetchOnlineAccounts().then(() => {
    // 等待账号加载完成后再加载标签
    initTags();
  });
  fetchFriendList();
})

// 打开标签管理对话框
const handleTagManagement = () => {
  console.log('标签管理按钮被点击');
  tagManagementDialogVisible.value = true;
  // 确保对话框显示
  if (!tagManagementDialogVisible.value) {
    setTimeout(() => {
      tagManagementDialogVisible.value = true;
      console.log('重试显示标签管理对话框');
    }, 100);
  }
  // 这里可以添加加载标签列表的逻辑
}

// 创建新标签
const handleCreateTag = async () => {
  if (!newTagName.value.trim()) {
    ElMessage.warning('标签名称不能为空')
    return
  }

  // 检查标签是否已存在
  const exists = allTags.value.some(tag => tag.name === newTagName.value.trim())
  if (exists) {
    ElMessage.warning('标签已存在')
    return
  }

  tagLoading.value = true;
  try {
    // 调用后端创建标签接口
    const response = await axios.post('/add/tag', {
      tag: newTagName.value.trim(),
      device_id: accountFilter.value
    });

    if (response.data.code === 200) {
      // 创建新标签对象，使用现有最大ID加一
      // 提取现有标签中的数字ID并找出最大值
      const maxId = allTags.value.reduce((max, tag) => {
        const num = parseInt(tag.id.toString()) || 0;
        return Math.max(max, num);
      }, 0);
      
      // 新ID为最大ID加一
      const newTag: Tag = {
        id: String(maxId + 1),
        name: newTagName.value.trim(),
        value: newTagName.value.trim(),
        type: 'default'
      };

      // 更新标签列表并确保客户标签在第一位
      const updatedTags = [...allTags.value, newTag];
      allTags.value = sortTags(updatedTags as Tag[]);

      ElMessage.success('标签创建成功')
      newTagName.value = ''
    } else {
      ElMessage.error('标签创建失败: ' + response.data.message)
    }
  } catch (error) {
    console.error('创建标签失败:', error);
    ElMessage.error('创建标签过程中发生错误')
  } finally {
    tagLoading.value = false;
  }
}

// 标签排序函数 - 确保客户标签在第一位
const sortTags = (tags: Tag[]) => {
  // 先筛选出客户标签
  const customerTag = tags.find(t => t.name === '客户');
  // 筛选出非客户标签
  const otherTags = tags.filter(t => t.name !== '客户');
  // 如果有客户标签，放在第一位，否则直接返回其他标签
  return customerTag ? [customerTag, ...otherTags] : otherTags;
}

// 删除标签
const handleDeleteTag = async (tag: Tag) => {
  ElMessageBox.confirm(
    `确定要删除标签"${tag.name}"吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    tagLoading.value = true;
    try {
      // 调用后端删除标签接口
      const response = await axios.post('/del/tag', {
        tag: tag.name,
        device_id: accountFilter.value
      });

      if (response.data.code === 200) {
        allTags.value = allTags.value.filter(t => t.id !== tag.id)
        ElMessage.success('标签删除成功')
      } else {
        ElMessage.error('标签删除失败: ' + response.data.message)
      }
    } catch (error) {
      console.error('删除标签失败:', error);
      ElMessage.error('删除标签过程中发生错误')
    } finally {
      tagLoading.value = false;
    }
  }).catch(() => {})
}

// 账号选项
const accountOptions = ref<Account[]>([])
const accountFilter = ref('')

// 标签编辑相关
const tagDialogVisible = ref(false)
const currentFriend = ref<Friend>({ id: 0, nickname: '', wxid: '', status: '', tags: [], account: '', accountName: '', accountAvatar: '' ,token_key: ''})
const selectedTag = ref('')

// 添加好友相关
const addDialogVisible = ref(false)
const newFriend = reactive({
  nickname: '',
  wxid: '',
  tags: [] as string[]
})


// 添加发送消息相关的状态
const messageDialogVisible = ref(false)
const messageContent = ref('')

// 检查当前选择的账号是否在线
const isAccountOnline = computed(() => {
  const selectedAccount = accountOptions.value.find(acc => acc.id === accountFilter.value)
  return selectedAccount?.status === 'online'
})

// 实现发送消息按钮点击事件
const handleSendMessage = () => {
  if (selectedFriends.value.length === 0) {
    ElMessage.warning('请先选择好友')
    return
  }
  messageContent.value = ''
  messageDialogVisible.value = true
}

// 实现发送消息确认事件
const handleSendMessageConfirm = async () => {
  if (!messageContent.value.trim()) {
    ElMessage.warning('消息内容不能为空')
    return
  }

  loading.value = true
  try {
    const friendIds = selectedFriends.value.map(friend => friend.wxid)
    // 调用后端发送消息接口
    const response = await axios.post('/wx_message/send', {
      to_users: friendIds,
      msg: messageContent.value,
      auth_key: currentTokenKey.value
    })

    if (response.data.code === 200) {
      ElMessage.success('消息发送成功')
      messageDialogVisible.value = false
    } else {
      ElMessage.error('消息发送失败，请稍后重试')
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息过程中发生错误')
  } finally {
    loading.value = false
  }
}

// 好友详情相关
const detailDialogVisible = ref(false)
const friendDetail = ref<any>(null)
const isEditingRemark = ref(false)
const editingRemark = ref('')

// 历史聊天记录相关
const historyDialogVisible = ref(false)
const chatHistory = ref<any[]>([])
const historyLoading = ref(false)


// 处理选择变化
const handleSelectionChange = (selection: Friend[]) => {
  selectedFriends.value = selection
}
// 批量标签移除相关
const batchRemoveTagDialogVisible = ref(false)
const selectedRemoveTag = ref('')

// 打开批量移除标签对话框
const openBatchRemoveTagDialog = () => {
  if (selectedFriends.value.length === 0) {
    ElMessage.warning('请先选择好友')
    return
  }
  batchRemoveTagDialogVisible.value = true
}

// 批量移除标签
const batchRemoveTags = async () => {
  if (!selectedRemoveTag.value) {
    ElMessage.warning('请选择要移除的标签')
    return
  }

  loading.value = true
  try {
    const friendIds = selectedFriends.value.map(friend => friend.wxid)
    const response = await axios.post('/wx_friends/remove/tags', {
      wx_ids: friendIds,
      tag: selectedRemoveTag.value,
      device_id: accountFilter.value
    })

    if (response.data.code == 200) {
      // 更新本地数据 - 移除标签
      selectedFriends.value.forEach(friend => {
        friend.tags = friend.tags.filter(tag => tag.name !== selectedRemoveTag.value);
      });

      customerResultSuccess.value = true
      customerResultMessage.value = `已成功为${selectedFriends.value.length}个好友移除标签: ${selectedRemoveTag.value}`
      fetchFriendList()
    } else {
      customerResultSuccess.value = false
      customerResultMessage.value = '移除标签失败，请稍后重试'
    }
    customerResultDialogVisible.value = true
    batchRemoveTagDialogVisible.value = false
  } catch (error) {
    console.error('批量移除标签失败:', error)
    ElMessage.error('批量移除标签失败')
  } finally {
    loading.value = false
  }
}


// 批量标签设置相关
const batchTagDialogVisible = ref(false)
const selectedBatchTag = ref('')

// 打开批量标签设置对话框
const openBatchTagDialog = () => {
  if (selectedFriends.value.length === 0) {
    ElMessage.warning('请先选择好友')
    return
  }
  batchTagDialogVisible.value = true
}

// 批量设置标签
const batchSetTags = async () => {
  if (!selectedBatchTag.value) {
    ElMessage.warning('请选择标签')
    return
  }

  loading.value = true
  try {
    const friendIds = selectedFriends.value.map(friend => friend.wxid)
    const response = await axios.post('/wx_friends/tags', {
      wx_ids: friendIds,
      tag: selectedBatchTag.value,
      device_id: accountFilter.value
    })

    if (response.data.code == 200) {
      customerResultSuccess.value = true
      customerResultMessage.value = `已成功为${selectedFriends.value.length}个好友设置标签: ${selectedBatchTag.value}`
      fetchFriendList()
    } else {
      customerResultSuccess.value = false
      customerResultMessage.value = '设置标签失败，请稍后重试'
    }
    customerResultDialogVisible.value = true
    batchTagDialogVisible.value = false
  } catch (error) {
    console.error('批量设置标签失败:', error)
    ElMessage.error('批量设置标签失败')
  } finally {
    loading.value = false
  }
}

// 设置为客户
const handleSetAsCustomer = async () => {
  if (selectedFriends.value.length === 0) {
    ElMessage.warning('请先选择好友')
    return
  }
  
  loading.value = true
  try {
    // 获取所有选中好友的ID
    const friendIds = selectedFriends.value.map(friend => friend.wxid)
    
        // 调用后端接口添加客户标签
    const response = await axios.post('/wx_friends/tags', {
      wx_ids: friendIds,
      tag: "客户",
      device_id: accountFilter.value // 添加当前账号ID作为参数
    })
    
    if (response.data.code == 200) {
      customerResultSuccess.value = true
      customerResultMessage.value = `已成功将${selectedFriends.value.length}个好友设置为客户`
    // 刷新好友列表以获取最新标签数据
      fetchFriendList()
    } else {
      customerResultSuccess.value = false
      customerResultMessage.value = '设置客户失败，请稍后重试'
    }
    
    customerResultDialogVisible.value = true
  } catch (error) {
    console.error('设置客户失败:', error)
    ElMessage.error('设置客户失败')
  } finally {
    loading.value = false
  }
}
const currentTokenKey = computed(() => {
  return accountOptions.value.find(acc => acc.id === accountFilter.value)?.auth_key || ''
})
// 获取在线账号列表
const fetchOnlineAccounts = async () => {
  accountsLoading.value = true
  try {
    const response = await axios.get('/wx_users')
    accountOptions.value = (response.data.data || []).map((acc: any) => ({
      id: acc.device_id,
      name: acc.nickname,
      avatar: acc.avatar,
      status: acc.status === 1 ? 'online' : 'offline',
      auth_key: acc.auth_key // 保留auth_key
    }))
  } catch (error) {
    accountOptions.value = []
  } finally {
    accountsLoading.value = false
  }
}

// 获取好友列表数据
const fetchFriendList = async () => {
  loading.value = true
  try {
    // 如果没有选择账号，显示提示
    if (!accountFilter.value) {
      friendList.value = []
      total.value = 0
      loading.value = false
      return
    }

    // 实际项目中应该调用后端API
    const response = await axios.get(`/wx_friends`, {
      params: {
        device_id: accountFilter.value,
        tag: tagFilter.value,
        nickname: searchQuery.value
      }
    })
    // 统一tags为对象数组并同步到allTags
    const rawList = response.data.data || []
    const processedList = rawList.map((friend: any, idx: number) => {
      const tags: Tag[] = Array.isArray(friend.tags)
        ? friend.tags.map((tagStr: string) => {
            // 确保标签存在于allTags中
            if (typeof tagStr === 'string') {
              let existingTag = allTags.value.find(t => t.name === tagStr);
              if (!existingTag) {
                const maxId = Math.max(...allTags.value.map(t => parseInt(t.id) || 0), 0);
                existingTag = { 
                  id: String(maxId + 1), 
                  name: tagStr, 
                  value: tagStr, 
                  type: 'default'
                };
                allTags.value = [...allTags.value, existingTag as Tag];
              }
              return existingTag;
            }
            return { id: `tag-${tagStr}`, name: String(tagStr), value: String(tagStr), type: 'default' } as Tag;
          })
        : [];
      return {
        id: idx + 1,
        nickname: friend.nickname,
        wxid: friend.wx_id,
        status: 'active', // 或 friend.status
        tags,
        account: accountFilter.value,
        accountName: accountOptions.value.find(acc => acc.id === accountFilter.value)?.name || '',
        accountAvatar: accountOptions.value.find(acc => acc.id === accountFilter.value)?.avatar || '',
        token_key: friend._id
      }
    })

    // 分页
    total.value = processedList.length
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    friendList.value = processedList.slice(start, end)
  } catch (error) {
    console.error('获取好友列表失败:', error)
    ElMessage.error('获取好友列表失败')
    friendList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  fetchFriendList()
}

// 处理页码变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchFriendList()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1 // 重置到第一页
  fetchFriendList()
}

// 处理账号选择变化
const handleAccountChange = () => {
  currentPage.value = 1 // 重置到第一页
  fetchFriendList()
}

// 处理查看详情
const handleViewDetail = async (row: Friend) => {
  loading.value = true;
  try {
    const response = await axios.get(`/wx_friends/detail`, {
      params: {
        key: currentTokenKey.value,
        wx_id: row.wxid,
        device_id: accountFilter.value
      }
    });
    friendDetail.value = response.data.data;
    detailDialogVisible.value = true;
    editingRemark.value = friendDetail.value.remark?.str || '';
  } catch (error) {
    ElMessage.error('获取好友详情失败');
    console.error('获取好友详情失败:', error);
  } finally {
    loading.value = false;
  }
};

// 处理删除
const handleDelete = (row: Friend) => {
  ElMessageBox.confirm(`确定要删除好友 ${row.nickname} 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟删除操作
    setTimeout(() => {
      friendList.value = friendList.value.filter(item => item.id !== row.id)
      ElMessage.success('删除成功')
    }, 300)
  }).catch(() => {})
}

// 处理编辑标签
// const handleEditTags = (row: Friend) => {
//   currentFriend.value = JSON.parse(JSON.stringify(row)) // 深拷贝
//   tagDialogVisible.value = true
// }

// 处理移除标签
const handleRemoveTag = (tag: Tag) => {
  currentFriend.value.tags = currentFriend.value.tags.filter(t => t.id !== tag.id)
}

// 处理添加标签
const handleAddTag = () => {
  if (!selectedTag.value) return
  
  // 检查是否已存在相同标签
  if (currentFriend.value.tags.some(tag => tag.value === selectedTag.value)) {
    ElMessage.warning('该标签已存在')
    return
  }
  
  // 添加标签
  const tagInfo = availableTags.value.find(t => t.value === selectedTag.value)
  currentFriend.value.tags.push({
    id: `tag-${selectedTag.value}-${Math.random().toString(36).substr(2, 9)}`,
    name: tagInfo?.label || selectedTag.value,
    value: selectedTag.value,
    type: ''
  })
  
  selectedTag.value = ''
}

// 保存标签更改
const saveTagChanges = () => {
  // 模拟保存操作
  const index = friendList.value.findIndex(item => item.id === currentFriend.value.id)
  if (index !== -1) {
    friendList.value[index].tags = currentFriend.value.tags
    ElMessage.success('标签更新成功')
    tagDialogVisible.value = false
  }
}

// 处理添加好友
const handleAddFriend = () => {
  Object.assign(newFriend, {
    nickname: '',
    wxid: '',
    tags: []
  })
  addDialogVisible.value = true
}

// 保存新好友
const saveFriend = () => {
  if (!newFriend.nickname || !newFriend.wxid) {
    ElMessage.warning('请填写必填项')
    return
  }
  
  // 模拟保存操作
  const newId = Math.max(...friendList.value.map(item => item.id), 0) + 1
  const friend = {
    id: newId,
    nickname: newFriend.nickname,
    wxid: newFriend.wxid,
    status: 'active',
    tags: newFriend.tags.map(value => {
      const tagInfo = availableTags.value.find(t => t.value === value)
      return {
        id: `tag-${value}-${Math.random().toString(36).substr(2, 9)}`,
        name: tagInfo?.label || value,
        value,
        type: ''
      }
    }),
    account: accountFilter.value, // 使用当前选择的账号
    accountName: accountOptions.value.find(acc => acc.id === accountFilter.value)?.name || '',
    accountAvatar: accountOptions.value.find(acc => acc.id === accountFilter.value)?.avatar || '',
    token_key: '' // 添加缺失的token_key字段
  }
  
  friendList.value.unshift(friend)
  total.value++
  ElMessage.success('添加好友成功')
  addDialogVisible.value = false
}

// 检查是否为JSON内容
const isJsonContent = (content: string): boolean => {
  if (!content || typeof content !== 'string') return false;
  
  try {
    // 尝试清理并解析JSON
    let cleanText = content.trim();
    // 移除可能的代码块标记
    cleanText = cleanText.replace(/^```json\s*|\s*```$/g, '');
    // 移除可能的逗号错误
    cleanText = cleanText.replace(/,\s*}\s*$/, '}').replace(/,\s*]\s*$/, ']');
    
    JSON.parse(cleanText);
    return true;
  } catch (e) {
    return false;
  }
};

// 格式化JSON内容
const formatJsonContent = () => {
  if (!editingRemark.value) return;
  
  try {
    let cleanText = editingRemark.value.trim();
    // 移除可能的代码块标记
    cleanText = cleanText.replace(/^```json\s*|\s*```$/g, '');
    // 移除可能的逗号错误
    cleanText = cleanText.replace(/,\s*}\s*$/, '}').replace(/,\s*]\s*$/, ']');
    
    const parsed = JSON.parse(cleanText);
    editingRemark.value = JSON.stringify(parsed, null, 2);
  } catch (e) {
    ElMessage.error('JSON格式化失败，请检查内容');
    console.error('JSON格式化失败:', e);
  }
};

// 压缩JSON内容
const minifyJsonContent = () => {
  if (!editingRemark.value) return;
  
  try {
    let cleanText = editingRemark.value.trim();
    // 移除可能的代码块标记
    cleanText = cleanText.replace(/^```json\s*|\s*```$/g, '');
    // 移除可能的逗号错误
    cleanText = cleanText.replace(/,\s*}\s*$/, '}').replace(/,\s*]\s*$/, ']');
    
    const parsed = JSON.parse(cleanText);
    editingRemark.value = JSON.stringify(parsed);
  } catch (e) {
    ElMessage.error('JSON压缩失败，请检查内容');
    console.error('JSON压缩失败:', e);
  }
};

// 处理编辑备注
const handleEditRemark = () => {
  isEditingRemark.value = true;
  editingRemark.value = friendDetail.value.remark?.str || '';
  
  // 如果内容是JSON且未格式化，自动尝试格式化
  if (isJsonContent(editingRemark.value) && !editingRemark.value.includes('\n')) {
    try {
      formatJsonContent();
    } catch (e) {
      // 忽略格式化错误
    }
  }
};

// 取消编辑备注
const cancelEditRemark = () => {
  isEditingRemark.value = false;
  editingRemark.value = friendDetail.value.remark?.str || '';
};

// 保存备注
const saveRemark = async () => {
  if (!editingRemark.value) {
    ElMessage.warning('备注信息不能为空');
    return;
  }

  loading.value = true;
  try {
    const response = await axios.post('/wx_friends/remark', {
      wx_id: friendDetail.value.userName?.str || '',
      remark: editingRemark.value,
      device_id: accountFilter.value
    });

    if (response.data.code == 200) {
      friendDetail.value.remark = { str: editingRemark.value };
      ElMessage.success('备注更新成功');
    } else {
      ElMessage.error('备注更新失败');
    }
  } catch (error) {
    ElMessage.error('备注更新失败');
    console.error('备注更新失败:', error);
  } finally {
    loading.value = false;
    isEditingRemark.value = false;
  }
};

// 处理查看历史聊天记录
const handleViewHistory = () => {
  if (!friendDetail.value || !friendDetail.value.userName?.str) {
    ElMessage.warning('无法获取微信ID，无法查看历史聊天记录');
    return;
  }
  fetchChatHistory();
  historyDialogVisible.value = true;
};

// 获取历史聊天记录
const fetchChatHistory = async () => {
  historyLoading.value = true;
  try {
    const response = await axios.get(`/message/history`, {
      params: {
        wx_id: friendDetail.value.userName?.str,
        device_id: accountFilter.value,
        start_time: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(), // 最近30天
        end_time: new Date().toISOString()
      }
    });
    chatHistory.value = response.data.data || [];
  } catch (error) {
    console.error('获取历史聊天记录失败:', error);
    ElMessage.error('获取历史聊天记录失败');
    chatHistory.value = [];
  } finally {
    historyLoading.value = false;
  }
};

// 格式化消息时间
const formatMessageTime = (timestamp: string) => {
  const date = new Date(timestamp);
  const now = new Date();
  const diffMinutes = (now.getTime() - date.getTime()) / (1000 * 60);

  if (diffMinutes < 60) {
    return `${Math.floor(diffMinutes)}分钟前`;
  } else if (diffMinutes < 24 * 60) {
    return `${Math.floor(diffMinutes / 60)}小时前`;
  } else {
    return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours()}:${date.getMinutes()}`;
  }
};

// 获取消息类型文本
const getMessageTypeText = (type: number) => {
  switch (type) {
    case 1:
      return '文本';
    case 2:
      return '图片';
    case 3:
      return '语音';
    case 4:
      return '视频';
    case 5:
      return '文件';
    case 6:
      return '位置';
    case 7:
      return '名片';
    case 8:
      return '链接';
    case 9:
      return '小程序';
    case 10:
      return '红包';
    case 11:
      return '转账';
    case 12:
      return '未知';
    default:
      return '未知';
  }
};

// 获取消息类型标签
const getMessageTypeTag = (type: number) => {
  switch (type) {
    case 1:
      return 'info';
    case 2:
      return 'success';
    case 3:
      return 'warning';
    case 4:
      return 'danger';
    case 5:
      return 'info';
    case 6:
      return 'info';
    case 7:
      return 'info';
    case 8:
      return 'info';
    case 9:
      return 'info';
    case 10:
      return 'info';
    case 11:
      return 'info';
    case 12:
      return 'info';
    default:
      return 'info';
  }
};

// 获取来源文本
const getSourceText = (source: number) => {
  switch (source) {
    case 1:
      return '微信好友';
    case 2:
      return '群聊';
    case 3:
      return '公众号';
    case 4:
      return '搜索';
    case 5:
      return '名片分享';
    case 6:
      return '扫描二维码';
    case 7:
      return '添加好友';
    case 8:
      return '群聊';
    case 9:
      return '手机通讯录';
    case 10:
      return '微信团队';
    case 11:
      return '微信支付';
    case 12:
      return '搜索';
    case 13:
      return '其他';
    default:
      return '未知';
  }
};

// 获取添加联系场景文本
const getAddContactSceneText = (scene: number) => {
  switch (scene) {
    case 1:
      return '未知';
    case 2:
      return '搜索';
    case 3:
      return '扫描二维码';
    case 4:
      return '名片分享';
    case 5:
      return '群聊';
    case 6:
      return '手机通讯录';
    case 7:
      return '微信团队';
    case 8:
      return '微信支付';
    case 9:
      return '其他';
    default:
      return '未知';
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchOnlineAccounts() // 加载账号选项
  fetchFriendList()
})
</script>

<style scoped lang="scss">
.friend-tags-container {
  padding: 20px;
}

.batch-operation-toolbar {
  margin: 15px 0;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  gap: 10px;
}

.batch-tag-container {
  padding: 20px 0;
}

.tag-select {
  width: 100%;
  margin-top: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-container {
  display: flex;
  gap: 15px;
  margin: 20px 0;
  flex-wrap: wrap;
}

.search-input {
  width: 250px; /* 设置固定宽度 */
}

.filter-select {
  width: 200px; /* 设置固定宽度 */
}

.filter-select {
  width: 180px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.tag-item {
  margin-right: 8px;
  margin-bottom: 8px;
}

.message-dialog-container {
  padding: 10px;
}

.recipient-info {
  margin-bottom: 15px;
}

.recipients {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}

.recipient-avatar {
  cursor: pointer;
}

.message-textarea {
  width: 100%;
}

.edit-tools {
  display: flex;
  gap: 8px;
}

.remark-edit .el-textarea__inner {
  font-family: 'Courier New', Courier, monospace;
  resize: vertical;
  min-height: 200px;
}

.tag-edit-container {
  padding: 10px;
}

.current-tags {
  margin-bottom: 15px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.add-tag {
  display: flex;
  gap: 10px;
  align-items: center;
}

.result-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.success-icon {
  color: #67c23a;
  margin-bottom: 15px;
}

.error-icon {
  color: #f56c6c;
  margin-bottom: 15px;
}

.friend-detail {
    padding: 10px;
  }

  /* Markdown样式 */
  .markdown-heading {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
    margin: 15px 0 10px 0;
    padding-bottom: 5px;
    border-bottom: 1px solid #e4e7ed;
  }
  
  .markdown-list {
    list-style-type: none;
    padding-left: 20px;
    margin: 10px 0;
  }
  
  .markdown-list li {
    position: relative;
    padding-left: 20px;
    margin-bottom: 8px;
    line-height: 1.6;
  }
  
  .markdown-list li:before {
    content: "•";
    position: absolute;
    left: 0;
    color: #606266;
    font-weight: bold;
  }
  
  .markdown-divider {
    border: none;
    border-top: 1px solid #e4e7ed;
    margin: 20px 0;
  }
  
  .remark-content strong {
    font-weight: bold;
    color: #303133;
  }
  
  .remark-content p {
    margin-bottom: 10px;
    line-height: 1.6;
    color: #606266;
  }
  
  .remark-content p:last-child {
    margin-bottom: 0;
  }
  
  /* 优化备注内容整体样式 */
  .remark-content {
    font-size: 14px;
    color: #606266;
    line-height: 1.6;
  }

.basic-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.name-info {
  display: flex;
  flex-direction: column;
}

.wxid {
  color: #606266;
  font-size: 14px;
}

.alias {
  color: #909399;
  font-size: 12px;
}

.status-info {
  display: flex;
  gap: 10px;
}

.detail-info {
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 12px;
  display: flex;
}

.info-item label {
  width: 80px;
  color: #606266;
}

.remark-section {
  margin-bottom: 20px;
}

.remark-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.no-remark {
  color: #909399;
}

.remark-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
  justify-content: flex-end;
}

.tags-section {
  margin-bottom: 10px;
}

.no-tags {
  color: #909399;
}

.loading-detail {
  padding: 20px;
}

/* 标签管理样式 */
.tag-management-container {
  padding: 15px;
}

.tag-creation {
  margin-bottom: 20px;
}

.tag-input {
  width: 300px;
}

.tag-list {
  margin-top: 20px;
}
.friend-tags-container {
    .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .search-container {
    display: flex;
    margin-bottom: 20px;
    gap: 10px;
    
    .search-input {
      width: 300px;
    }

    .filter-select {
      width: 200px;
    }

    .account-option {
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .account-avatar {
      flex-shrink: 0;
    }

    .account-status {
      margin-left: 8px;
    }

    .empty-data {
      text-align: center;
      padding: 10px 0;
      color: #909399;
    }
  }
  
  .tag-item {
    margin-right: 5px;
    margin-bottom: 5px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .tag-edit-container {
    .current-tags {
      margin-bottom: 15px;
      
      span {
        margin-right: 10px;
      }
      
      .el-tag {
        margin-right: 5px;
      }
    }
    
    .add-tag {
      display: flex;
      gap: 10px;
    }
  }
  
  .result-message {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 0;
    
    .success-icon {
      color: #67c23a;
      margin-bottom: 15px;
    }
    
    .error-icon {
      color: #f56c6c;
      margin-bottom: 15px;
    }
    
    p {
      font-size: 16px;
    }
  }
  
  .account-info {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .account-avatar {
      flex-shrink: 0;
    }
  }

  .friend-detail {
    .basic-info {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      gap: 20px;

      .avatar-section {
        display: flex;
        align-items: center;
        gap: 15px;

        .name-info {
          h3 {
            margin-bottom: 5px;
            font-size: 24px;
          }
          p {
            color: #606266;
            font-size: 14px;
          }
          .wxid {
            font-weight: bold;
          }
          .alias {
            color: #909399;
            font-size: 14px;
          }
        }
      }

      .status-info {
        display: flex;
        gap: 10px;
      }
    }

    .detail-info {
      .info-item {
        margin-bottom: 10px;
        label {
          font-weight: bold;
          margin-right: 10px;
        }
        span {
          font-size: 16px;
        }
      }
    }

    .remark-section {
      .remark-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
        h4 {
          margin-bottom: 0;
        }
        .remark-actions {
          display: flex;
          gap: 10px;
        }
      }
      .remark-content {
        font-size: 16px;
        color: #606266;
        p {
          margin-bottom: 10px;
        }
        .no-remark {
          color: #909399;
        }
      }
      .remark-edit {
        .el-textarea {
          margin-bottom: 10px;
        }
        .remark-actions {
          display: flex;
          justify-content: flex-end;
          gap: 10px;
        }
      }
    }

    .tags-section {
      .current-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        .tag-item {
          font-size: 14px;
        }
        .no-tags {
          color: #909399;
          font-size: 14px;
        }
      }
    }

    .loading-detail {
      padding: 20px;
    }
  }

  .history-dialog {
    .chat-history {
      max-height: 500px;
      overflow-y: auto;
      padding: 10px;
      .message-item {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        margin-bottom: 15px;
        .message-time {
          font-size: 12px;
          color: #909399;
          margin-bottom: 5px;
        }
        .message-content {
          display: flex;
          align-items: flex-start;
          gap: 8px;
          padding: 8px 12px;
          border-radius: 8px;
          max-width: 70%;
          word-break: break-word;
        }
        &.sent {
          align-items: flex-end;
          .message-content {
            background-color: #e1f3d8;
            color: #389e0d;
            align-self: flex-end;
          }
        }
        &.received {
          align-items: flex-start;
          .message-content {
            background-color: #f3f3f3;
            color: #303133;
            align-self: flex-start;
          }
        }
      }
    }
    .loading-history {
      padding: 20px;
    }
    .empty-history {
      padding: 20px;
    }
  }
}
</style>